package com.example.lotterysystem.controller;

import com.example.lotterysystem.common.errorcode.ControllerErrorCodeConstants;
import com.example.lotterysystem.common.exception.ControllerException;
import com.example.lotterysystem.common.result.CommonResult;
import com.example.lotterysystem.common.util.JacksonUtil;
import com.example.lotterysystem.controller.param.MessageLoginParam;
import com.example.lotterysystem.controller.param.UserPasswordLoginParam;
import com.example.lotterysystem.controller.param.UserRegisterParam;
import com.example.lotterysystem.controller.result.BaseUserInfoResult;
import com.example.lotterysystem.controller.result.UserLoginResult;
import com.example.lotterysystem.controller.result.UserRegisterResult;
import com.example.lotterysystem.service.UserService;
import com.example.lotterysystem.service.dto.UserDTO;
import com.example.lotterysystem.service.dto.UserLoginDTO;
import com.example.lotterysystem.service.dto.UserRegisterDTO;
import com.example.lotterysystem.service.enums.UserIdentityEnum;
import com.example.lotterysystem.service.impl.VerificationCodeServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@RestController
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserService userService;
    @Autowired
    private VerificationCodeServiceImpl verificationCodeService;
    /**
     * 注册
     * @param param
     * @return CommonResult<UserRegisterResult>
     */
    @RequestMapping("/register")
    public CommonResult<UserRegisterResult> userRegisterResult(@Validated @RequestBody UserRegisterParam param){
        //@RequestBody 接收前端的json对象      @Validated对参数进行验证
        //日志打印(请求参数相关的内容)
        logger.info("userRegisterResult UserRegisterParam:{}", JacksonUtil.writeValueAsString(param));//用json来进行输出
        //调用service层服务,进行访问
        UserRegisterDTO userRegisterDTO = userService.register(param);
        return CommonResult.success(convertToUserRegisterResult(userRegisterDTO));
    }
    /**
     * 发送验证码
     * @param phoneNumber
     * @return CommonResult<Boolean>
     */
    @RequestMapping("/verification-code/send")
    public CommonResult<Boolean> sendVerificationCode(String phoneNumber){
        logger.info("sendVerificationCode phongNumber:",phoneNumber);
        verificationCodeService.sendVerificationCodeService(phoneNumber);
        return CommonResult.success(Boolean.TRUE);
    }

    /**
     * 密码登录
     * @param param
     * @return ${RETURN_DESCRIPTION}
     */
    @RequestMapping("/password/login")
    public CommonResult<UserLoginResult> userLogin(@Validated@RequestBody UserPasswordLoginParam param){
        logger.info("userLogin UserPasswordLoginParam : ",JacksonUtil.writeValueAsString(param));
        UserLoginDTO userLoginDTO = userService.login(param);
        return CommonResult.success(convertToUserLoginResult(userLoginDTO));
    }


    /**
     * 验证码登录
     * @param param
     * @return ${RETURN_DESCRIPTION}
     */
    @RequestMapping("/message/login")
    public CommonResult<UserLoginResult> messageLogin(@Validated@RequestBody MessageLoginParam param){
        logger.info("messageLogin MessageLoginParam : ",JacksonUtil.writeValueAsString(param));
        UserLoginDTO userLoginDTO = userService.login(param);
        return CommonResult.success(convertToUserLoginResult(userLoginDTO));
    }

    /**
     * 通过userId进行删除
     */
    @RequestMapping("/user/delete")
    private CommonResult<Boolean> deleteUser(Long userId){
        logger.info("deleteUser userId:{}",userId);
        return CommonResult.success(userService.deleteUser(userId));
    }

    @RequestMapping("/base-user/find-list")
    public CommonResult<List<BaseUserInfoResult>> findBaseUserInfo(String identity) {
        logger.info("findBaseUserInfo identity:{}",identity);
        List<UserDTO> userDTOList = userService.findUserInfo(UserIdentityEnum.forName(identity));
        return CommonResult.success(ConvertToList(userDTOList));
    }

    private List<BaseUserInfoResult> ConvertToList(List<UserDTO> userDTOList) {
        if(CollectionUtils.isEmpty(userDTOList)){
            return Arrays.asList();
        }
        return userDTOList.stream().map(userDTO -> {
            BaseUserInfoResult result = new BaseUserInfoResult();
            result.setUserId(userDTO.getUserId());
            result.setUserName(userDTO.getUserName());
            result.setIdentity(userDTO.getIdentity().name());
            return result;
        }).toList();
    }

    private UserLoginResult convertToUserLoginResult(UserLoginDTO userLoginDTO) {
        if(null==userLoginDTO){
            throw new ControllerException(ControllerErrorCodeConstants.LOGIN_ERROR);
        }
        UserLoginResult userLoginResult = new UserLoginResult();
        userLoginResult.setToken(userLoginDTO.getToken());
        userLoginResult.setIdentity(userLoginDTO.getIdentity().name());
        return userLoginResult;
    }

    private UserRegisterResult convertToUserRegisterResult(UserRegisterDTO userRegisterDTO) {
        UserRegisterResult result = new UserRegisterResult();
        if (null==userRegisterDTO){
            throw new ControllerException(ControllerErrorCodeConstants.REGISTER_ERROR);
        }

        result.setUserId(userRegisterDTO.getUserId());
        return result;
    }
}
